import { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, Text, Image, Button } from '@tarojs/components'

import * as api from 'src/api'
import OrderGoods from 'src/components/OrderGoods'
import withPage from 'src/utils/withPage'

import './index.scss'

type IProps = {}

type IState = {
  orderInfo: { [key: string]: any }
}

interface Index {
  props: IProps
  state: IState
  orderId: string
}

@withPage()
class Index extends Component {
  state: IState = {
    orderInfo: {},
  }

  onLoad(options) {
    if (!options.order_id) {
      return Taro.showToast({
        title: '缺少参数无法查看订单详情',
      })
    }
    this.orderId = options.order_id
    this.getOrderDetail()
  }

  getOrderDetail = async () => {
    Taro.showLoading({
      title: '正在加载中',
    })
    const res = await api.getOrder(this.orderId)
    let cartInfo: any[] = []
    res.cartInfo.forEach((item: any) => {
      cartInfo.push(item.info)
    })
    const { code: codeImg } = await api.qrcodeApi({
      height: '145',
      text: res.verifyCode,
      width: '145',
    })
    this.setState({ orderInfo: { ...(res || {}), cartInfo, codeImg } })
    Taro.hideLoading()
  }

  makePhoneCall = () => {
    Taro.makePhoneCall({ phoneNumber: this.state.orderInfo.shop?.telephone })
  }

  showStoreQrCode = () => {
    Taro.previewImage({
      current: '0',
      urls: [this.state.orderInfo.shop?.imageUrl],
    })
  }

  cancelOrder = () => {
    const that = this
    Taro.showModal({
      title: '提示',
      content: '确认取消该订单?',
      success: async (res) => {
        if (res.confirm) {
          await api.orderCancel(that.state.orderInfo.id)
          Taro.showToast({ title: '取消成功', icon: 'success' })
          this.getOrderDetail()
        }
      },
    })
  }

  confirmOrder = () => {
    const that = this
    Taro.showModal({
      title: '确认收货',
      content: '为保障权益，请收到货确认无误后，再确认收货。',
      success: async (res) => {
        if (res.confirm) {
          await api.orderTake(that.state.orderInfo.id)
          Taro.showToast({ title: '操作成功', icon: 'success' })
          this.getOrderDetail()
        }
      },
    })
  }

  copy = (value) => {
    Taro.setClipboardData({ data: value })
  }

  render() {
    const { orderInfo } = this.state
    return (
      <View className="order-detail">
        <View className="header at-row at-row__justify--between at-row__align--center">
          <View className="pictrue">
            <Image src={orderInfo.statusPic}></Image>
          </View>
          <View className="data">
            <View className="state">{orderInfo.pstatus?.msg}</View>
            <View>{orderInfo.createTime}</View>
          </View>
        </View>
        <View className="wrapper">
          <View className="info">
            {`${orderInfo.shippingType === 1 ? '付款门店' : '自提门店'}：${
              orderInfo.shop?.name || ''
            }`}
          </View>
          <View className="info">地址：{orderInfo.shop?.address || ''}</View>
          <View className="info">
            电话：
            <Text className="link" onClick={this.makePhoneCall}>
              {orderInfo.shop?.telephone || ''}
            </Text>
            <Text className="link" onClick={() => this.showStoreQrCode()}>
              查看门店二维码
            </Text>
          </View>
          <View className="info">门店营业时间：{orderInfo.shop?.dayTime}</View>
        </View>
        <View className="wrapper">
          <View className="info">
            {`${orderInfo.shippingType === 1 ? '收件人' : '提货人'}：${
              orderInfo.realName || ''
            }  ${orderInfo.userPhone || ''}`}
          </View>
          {orderInfo.shippingType === 1 && (
            <View className="info">地址：{orderInfo.userAddress}</View>
          )}
        </View>
        {orderInfo.shippingType === 2 && orderInfo.pstatus?.type === 1 && (
          <View className="wrapper">
            <View className="info">提货信息：提货时请出示以下核销码</View>
            <View className="verification">
              <View className="grayBg">
                <Image className="qr-code" src={orderInfo.codeImg}></Image>
              </View>
              <Image
                className="gear"
                src={require('src/static/images/writeOff.jpg')}
              ></Image>
              <View className="num">{orderInfo.verifyCode}</View>
            </View>
            <View className="info">
              核销时间：每日{orderInfo.shop?.dayTime}
            </View>
            <View className="info">
              使用说明：可将二维码出示给店员扫描或提供数字核销码
            </View>
          </View>
        )}
        {orderInfo.deliveryType === 'express' && (
          <View className="wrapper">
            <View className="info">
              快递公司：{orderInfo.deliveryName || ''}
            </View>
            <View className="info">
              快递号：{orderInfo.deliveryId || ''}
              {orderInfo.deliveryId && (
                <Text
                  className="copy"
                  onClick={() => this.copy(orderInfo.deliveryId)}
                >
                  复制
                </Text>
              )}
            </View>
          </View>
        )}
        <OrderGoods cartInfo={orderInfo.cartInfo} />
        <View className="wrapper">
          {orderInfo.userMarkPrice && (
            <View className="item">
              <View>优惠：</View>
              <View className="conter">-￥{orderInfo.userMarkPrice}</View>
            </View>
          )}
          <View className="item total-price">
            <View>实付金额：</View>
            <Text className="price price-color">￥{orderInfo.payPrice}</Text>
          </View>
          <Button
            className="contact remove-button-style"
            open-type="contact"
            hover-className="none"
          >
            联系客服
          </Button>
        </View>
        <View className="wrapper">
          <View className="item">
            <View>订单编号：</View>
            <View className="conter at-row at-row__justify--end">
              {orderInfo.orderId}
              <Text
                className="copy"
                onClick={() => this.copy(orderInfo.orderId)}
              >
                复制
              </Text>
            </View>
          </View>
          <View className="item">
            <View>下单时间：</View>
            <View className="conter">{orderInfo.createTime}</View>
          </View>
          <View className="item">
            <View>支付状态：</View>
            <View className="conter">
              {orderInfo.paid ? '已支付' : '未支付'}
            </View>
          </View>
          <View className="item">
            <View>支付方式：</View>
            <View className="conter">{orderInfo.pstatus?.payType}</View>
          </View>
          {orderInfo.mark && (
            <View className="item">
              <View>买家留言：</View>
              <View className="conter">{orderInfo.mark}</View>
            </View>
          )}
        </View>
        <View style={{ height: 60 }}></View>
        <View className="footer at-row at-row__justify--end at-row__align--center">
          {orderInfo.pstatus?.type === 0 && (
            <View className="qs-btn" onClick={this.cancelOrder}>
              取消订单
            </View>
          )}
          {orderInfo.pstatus?.type === 2 && (
            <View className="bnt bg-color" onClick={this.confirmOrder}>
              确认收货
            </View>
          )}
        </View>
      </View>
    )
  }
}

export default Index
